package top.loonglove.bean;

import top.loonglove.utils.ElementUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

/**
 * @author 向贵龙
 * @date 2021/7/12
 * MarkDown实体类
 */
public class MarkDown {
    /**
     * markdown内容标签
     */
    private List<AbstractElement> values;
    /**
     * 标签内容保存或者读取的文件
     */
    private File markDownFile = null;


    public MarkDown() {
    }

    public MarkDown(File markDownFile) {
        this.markDownFile = markDownFile;
    }

    public MarkDown(List<AbstractElement> values, File markDownFile) {
        this.values = values;
        this.markDownFile = markDownFile;
    }

    /**
     * 从初始化文件中加载markdown
     * @throws IOException 文件读取异常
     */
    public void loadFile() throws IOException {
        this.values = ElementUtils.fileCovertToElements(markDownFile);
    }

    /**
     * 从文件中加载markdown内容
     * @param file md文件
     * @throws IOException 文件读取异常
     */
    public void loadFile(File file) throws IOException {
        this.values = ElementUtils.fileCovertToElements(file);
    }

    public MarkDown(List<AbstractElement> values) {
        this.values = values;
    }

    public List<AbstractElement> getValues() {
        return values;
    }

    public void setValues(List<AbstractElement> values) {
        this.values = values;
    }

    public File getMarkDownFile() {
        return markDownFile;
    }

    public void setMarkDownFile(File markDownFile) {
        this.markDownFile = markDownFile;
    }

    /**
     * 将markdown写入文件
     * @param file 写入文库对象
     * @throws IOException 文件读取异常
     */
    public void writeToFile(File file) throws IOException {
        if (file==null){
            throw new FileNotFoundException("markDown File is Not Create,Please use other two arg method!");
        }else{
            if (!markDownFile.exists()){
                boolean flag = markDownFile.createNewFile();
                if (!flag){
                    throw new FileNotFoundException("markDown File Create Error!");
                }
            }
            try ( FileWriter fw =new FileWriter(markDownFile)){
                for (AbstractElement element:values){
                    fw.write(element.toString()+"\n");
                    fw.flush();
                }
            }
        }
    }

    /**
     * markdown写入文件
     * @param dir 写入文件路径
     * @param fileName 写入文件路径名
     * @throws IOException 文件读取异常
     */
    public void writeToFile(String dir, String fileName) throws IOException {
        markDownFile = new File(dir+fileName+".md");
        writeToFile();
    }

    /**
     * markdown写入初始化文件
     * @throws IOException 文件写入异常
     */
    public void writeToFile() throws IOException {
        writeToFile(markDownFile);
    }

    /**
     * markdown转为HTML标签 待优化
     * @return HTML文档
     */
    public String toDefaultHtml(){
        return ElementUtils.elementsToHtml(values);
    }


}
